package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * AOP获得操作日志
 */
@Slf4j
//@Aspect
@Component
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    //获得请求对象
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.annotation.Log)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {

        //操作人ID ---JWT中  获得请求头中的token:令牌信息
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operatorId = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operatorTime = LocalDateTime.now();
        //目标对象的类名
        String className = pjp.getTarget().getClass().getName();
        //目标方法名
        String methodName = pjp.getSignature().getName();
        //目标方法的参数
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);
        //目标方法的执行结果
        long begin = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        String returnValue = result.toString();
        //方法执行耗时
        long costTime = end - begin;

//        String operateName = (String) claims.get("name");
        OperateLog operateLog = new OperateLog(null, operatorId, operatorTime, className, methodName, methodParams, returnValue, costTime, null);
        operateLogMapper.insert(operateLog);


        return result;
    }
}
